import { useState, useEffect, useRef } from 'react';
import { Form, Notification, Table, Button, Space, Upload } from 'antd';
import { goBack, componentsMap } from '@/utils/util';
import API from '@/api';
import { connect, useDispatch, useModel } from 'umi';
import UploadList from '@/components/UploadList';
import FileList from '@/components/FileLists';
import EditableTable from '@/components/EditableTable';
import moment from 'moment';
const PlanComponent = ({ id, orgList, status }) => {
  const { initialState = {} } = useModel('@@initialState');
  const { orgId } = initialState.info;
  const tableRef = useRef();
  const formList = [
    {
      label: '单位名称',
      name: 'orgId',
      type: 'select',
      otherProps: {
        options: orgList,
        disabled: true,
      },
      rules: [
        {
          required: true,
          message: '请选择所属单位',
        },
      ],
    },
    {
      label: '预算额度',
      name: 'ysed',
      rules: [
        {
          required: true,
          pattern:
            /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/,
          message: '请输入正确的预算额度',
        },
      ],
    },
    {
      label: '预算年度',
      type: status === '0' ? 'datepicker' : 'input',
      name: 'ysnd',
      rules: [
        {
          required: true,
          message: '请选择预算年度',
        },
      ],
      otherProps: {
        picker: 'year',
      },
    },
    {
      label: '备注说明',
      name: 'remark',
      type: 'textarea',
      isBlock: true,
    },
  ];
  const [form] = Form.useForm();
  const [fileList, setfileList] = useState([]);
  const [editData, setEditData] = useState(null);
  const [currentData, setCurrentData] = useState({});
  const dispatch = useDispatch();
  const initOrgList = () => {
    dispatch({
      type: 'dict/queryOrgList',
      payload: {
        orgId,
      },
    });
  };
  if (!orgList) {
    initOrgList();
  }
  const uploadOptions = {
    fileTypes: [
      'application/doc',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ],
    maxSize: 50,
    maxNum: 3,
    accept: [
      '.doc,.docx.,.pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,',
    ],
    acceptMessage: 'word/pdf',
  };
  const initDetail = () => {
    API.showEB({
      id,
    }).then((res) => {
      if (res?.t) {
        const {
          ysnd,
          ysed,
          remark,
          orgId,
          emergencyBudgetFiles,
          emergencyBudgetDetails,
          orgName,
        } = res.t;
        setfileList(emergencyBudgetFiles);
        if (emergencyBudgetDetails) {
          setEditData(
            emergencyBudgetDetails.map((x) => ({
              ...x,
              doTime: moment(x.doTime).format('YYYY-MM-DD'),
              orgName,
              ysed,
            })),
          );
        }

        setCurrentData({
          orgName,
          ysed,
        });
        form.setFieldsValue({
          ysnd,
          ysed,
          remark,
          orgId,
          emergencyBudgetDetails,
        });
      }
    });
  };
  useEffect(() => {
    if (id) {
      initDetail();
    } else {
      form.setFieldsValue({
        orgId,
      });
    }
  }, [id]);

  const saveFn = (values) => {
    let request = API.addEB;
    if (id) {
      values.id = id;
      values.emergencyBudgetFiles = fileList;
      request = API.modEB;
      const fields = tableRef.current.getData().filter((x) => x.doTime);
      const hasError = fields.some((x) => x.errInfo?.errorFields.length > 0);
      if (hasError) {
        return;
      }
      values.emergencyBudgetDetails = [...fields];
    } else {
      values.ysnd = values.ysnd.format('YYYY');
    }
    const title = !id ? '新增' : '更新';
    request(values).then((res) => {
      if (res) {
        Notification.success({
          message: title + '成功',
        });
        goBack();
      }
    });
  };
  const downloadFn = (item) => {
    const downloadUrl = '/emergencyBudget/download';
    const params = {
      fileName: item.fileName,
      originalFileName: item.originalFileName,
    };
    API.downloadFn(downloadUrl, params);
  };

  const editColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, r, index) => index + 1,
    },
    {
      title: '单位名称',
      dataIndex: 'orgName',
      align: 'center',
    },
    {
      title: '预算额度(元)',
      dataIndex: 'ysed',
      align: 'center',
    },
    {
      title: '预算执行百分比(%)',
      dataIndex: 'yszxbfb',
      align: 'center',
      editable: true,
      type: 'input',
      rules: {
        pattern: /^([0-9]{1,2}$)|(^[0-9]{1,2}\.[0-9]{1,2}$)|100$|100.00$/,
        message: '请输入0-100的数值',
      },
    },
    {
      title: '执行时间',
      dataIndex: 'doTime',
      align: 'center',
      editable: true,
      rules: {
        type: 'any',
      },
      type: 'datepicker',
    },
    {
      title: '备注',
      dataIndex: 'reason',
      align: 'center',
      type: 'input',
      editable: true,
    },
    {
      title: '附件',
      dataIndex: 'originalFileName',
      type: 'file',
      align: 'center',
      render: (t, r) => <a onClick={downloadFn.bind(null, r)}>{t}</a>,
    },
  ];

  const detailColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, r, index) => index + 1,
    },
    {
      title: '单位名称',
      dataIndex: 'orgName',
      align: 'center',
    },
    {
      title: '预算额度(元)',
      dataIndex: 'ysed',
      align: 'center',
    },
    {
      title: '预算执行百分比(%)',
      dataIndex: 'yszxbfb',
      align: 'center',
    },
    {
      title: '执行时间',
      dataIndex: 'doTime',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'reason',
      align: 'center',
      type: 'input',
    },
    {
      title: '附件',
      dataIndex: 'originalFileName',
      type: 'file',
      align: 'center',
      render: (t, r) => <a onClick={downloadFn.bind(null, r)}>{t}</a>,
    },
  ];
  const { orgName, ysed } = currentData;
  const newData = {
    orgName,
    ysed,
    yszxbfb: '',
    doTime: null,
    reason: '',
  };

  return (
    <div className="main-x readOnly-x">
      <Form form={form} onFinish={saveFn}>
        <div className="base-title">预算信息</div>
        <div className="bgf">
          <div className="ant-form-inline form-x max-x">
            {formList.map((item) => {
              return (
                <Form.Item
                  key={item.name}
                  label={item.label}
                  name={item.name}
                  className={item.isBlock ? 'block' : ''}
                  rules={item.rules}
                >
                  {componentsMap(item.type, item.otherProps, status !== '0')}
                </Form.Item>
              );
            })}
            {status !== '0' ? (
              <Form.Item label="附件信息" className="block">
                {
                  <FileList
                    fileList={fileList}
                    downloadUrl="/emergencyBudget/download"
                  />
                }
              </Form.Item>
            ) : (
              <Form.Item
                label="附件信息"
                extra="支持word/pdf格式,单个大小在50M以内"
                name="emergencyBudgetFiles"
                className="block"
              >
                <UploadList
                  uploadUrl="/emergencyBudget/fileUpload"
                  downloadUrl="/emergencyBudget/download"
                  options={uploadOptions}
                  defaultFiles={fileList}
                ></UploadList>
              </Form.Item>
            )}
          </div>
        </div>
        {status === '0' ? (
          ''
        ) : (
          <>
            <div className="base-title mt20">处置结果</div>
            <div className="bgf mt20">
              {status === '2' ? (
                <EditableTable
                  columns={editColumns}
                  newData={newData}
                  defaultData={editData}
                  uploadUrl="/emergencyBudget/fileUpload"
                  ref={tableRef}
                ></EditableTable>
              ) : (
                <Table
                  columns={detailColumns}
                  dataSource={editData}
                  rowKey="id"
                  pagination={false}
                ></Table>
              )}
            </div>
          </>
        )}

        <div className="footer-x">
          {status !== '1' ? (
            <Space size={18}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button type="primary" className="cancel-btn" onClick={goBack}>
                返回
              </Button>
            </Space>
          ) : (
            <Button type="primary" className="cancel-btn" onClick={goBack}>
              返回
            </Button>
          )}
        </div>
      </Form>
    </div>
  );
};

export default connect(({ dict }) => ({
  planTypes: dict.planTypes,
  planOptions: dict.planOptions,
  orgList: dict.orgList,
}))(PlanComponent);
